﻿using System;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.Reflection;
using Caliburn.Micro.BikeWizard.Utils;

namespace Caliburn.Micro.BikeWizard.Utils
{
    /// <summary>
    /// Helps with the sequential execution of IResult implementations 
    /// 
    /// Notes: 
    /// 
    /// 1) Thin wrapper around the SequentialResult class, similar to the static Coroutine class.
    /// 2) a CoroutineExecutor will wait forever if one of the IResult implementions fails to fire a Completed event.
    /// </summary>
    public class CoroutineExecutor : IResult
    {
        #region Private Members
        private IEnumerable<IResult> actionResults;
        #endregion

        #region IResult Implementation
        public void Execute(ActionExecutionContext context)
        {
            SequentialResult executor = new SequentialResult(actionResults.GetEnumerator());
            executor.Completed += (sender, e) =>
                {
                    if (e.Error != null)
                        throw e.Error;
                    else
                        Completed(sender, e);
                };
            executor.Execute(null);
        }

        public event EventHandler<ResultCompletionEventArgs> Completed = delegate { };
        #endregion

        #region Constructors
        public CoroutineExecutor(IResult actionResult) : this(new List<IResult>() { actionResult })
        {
        }

        public CoroutineExecutor(params IResult[] actionResults) : this(new List<IResult>(actionResults))
        {
        }

        public CoroutineExecutor(IEnumerable<IResult> actionResults)
        {
            this.actionResults = actionResults;
        }
        #endregion
    }
}
